'use client'

import { useState, useRef, useCallback, useMemo, useEffect } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Badge } from "@/components/ui/badge"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Progress } from "@/components/ui/progress"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { 
  IconCamera, 
  IconUpload, 
  IconCheck, 
  IconUserCheck, 
  IconUser, 
  IconRefresh, 
  IconDatabase, 
  IconPill,
  IconScan,
  IconFilter,
  IconDownload,
  IconEye,
  IconFileText,
  IconTrendingUp,
  IconSearch,
  IconId,
  IconIdBadge2,
  IconAlertTriangle,
  IconTrash,
  IconX
} from "@tabler/icons-react"
import { recognizeDrugLabel, recognizeDoctorId, recognizePatientId, generateMockDrugInfo, generateMockDoctorInfo, generateMockPatientInfo, DrugInfo, MedicalIdInfo } from '@/lib/api/ocr'
import ocrService, { OCRRecord as ApiOCRRecord } from '@/lib/ocrService'
import { toast } from 'sonner'

// OCR记录类型 - 扩展API记录类型
interface OcrRecord extends Omit<ApiOCRRecord, 'type'> {
  type: 'drug_info' | 'medical_id' | 'document' | 'general' | 'drug' | 'doctor' | 'patient'
  status: 'success' | 'failed' | 'pending'
  data: any
  timestamp: string
  processedBy?: string
}

// 生成模拟OCR记录
const generateMockOcrData = (): OcrRecord[] => {
  const records: OcrRecord[] = []
  const types: ('drug' | 'doctor' | 'patient')[] = ['drug', 'doctor', 'patient']
  const statuses: ('success' | 'failed' | 'pending')[] = ['success', 'failed', 'pending']
  
  for (let i = 0; i < 20; i++) {
    const type = types[Math.floor(Math.random() * types.length)]
    const status = statuses[Math.floor(Math.random() * statuses.length)]
    const timestamp = new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000).toISOString()
    
    let data: any = {}
    
    switch (type) {
      case 'drug':
        data = {
          name: `药物${i + 1}`,
          specification: '0.25g×12粒',
          manufacturer: '制药公司',
          batchNumber: `A2024${String(i + 1).padStart(3, '0')}`,
          expiryDate: '2027-12-31'
        }
        break
      case 'doctor':
        data = {
          name: `医生${i + 1}`,
          id: `DOC${String(i + 1).padStart(3, '0')}`,
          department: ['内科', '外科', '儿科', '妇科'][Math.floor(Math.random() * 4)],
          position: ['主治医师', '副主任医师', '主任医师'][Math.floor(Math.random() * 3)],
          licenseNumber: `L110020240${String(i + 1).padStart(3, '0')}`
        }
        break
      case 'patient':
        data = {
          name: `患者${i + 1}`,
          id: `11010119900101${String(i + 1).padStart(4, '0')}`,
          phoneNumber: `138-8888-${String(i + 1).padStart(4, '0')}`,
          visitType: ['门诊', '急诊', '住院'][Math.floor(Math.random() * 3)]
        }
        break
    }
    
    records.push({
      id: `ocr-${i + 1}`,
      type,
      timestamp,
      status,
      data,
      confidence: Math.random() * 0.3 + 0.7,
      processedBy: `用户${Math.floor(Math.random() * 5) + 1}`
    })
  }
  
  return records.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime())
}

export default function OcrDashboard() {
  const [activeOcrTab, setActiveOcrTab] = useState('overview')
  const [records, setRecords] = useState<OcrRecord[]>([])
  const [isLoading, setIsLoading] = useState(false)
  const [recordsLoading, setRecordsLoading] = useState(false)
  const [uploadProgress, setUploadProgress] = useState(0)
  const [searchTerm, setSearchTerm] = useState('')
  const [typeFilter, setTypeFilter] = useState<string>('all')
  const [statusFilter, setStatusFilter] = useState<string>('all')
  const [currentPage, setCurrentPage] = useState(1)
  const [totalPages, setTotalPages] = useState(1)
  
  // 药物识别相关状态
  const [drugInfo, setDrugInfo] = useState<DrugInfo | null>(null)
  const [editedDrugInfo, setEditedDrugInfo] = useState<DrugInfo | null>(null)
  const [drugInventory, setDrugInventory] = useState<DrugInfo[]>([])
  
  // 医生认证相关状态
  const [doctorInfo, setDoctorInfo] = useState<MedicalIdInfo | null>(null)
  const [editedDoctorInfo, setEditedDoctorInfo] = useState<MedicalIdInfo | null>(null)
  const [authRecords, setAuthRecords] = useState<any[]>([])
  
  // 患者登记相关状态
  const [patientInfo, setPatientInfo] = useState<MedicalIdInfo | null>(null)
  const [editedPatientInfo, setEditedPatientInfo] = useState<MedicalIdInfo | null>(null)
  const [patientRecords, setPatientRecords] = useState<any[]>([])
  
  // 图片上传相关状态
  const [selectedImage, setSelectedImage] = useState<File | null>(null)
  const [imagePreview, setImagePreview] = useState<string | null>(null)
  const fileInputRef = useRef<HTMLInputElement>(null)
  
  // OCR设置
  const [useParallelRecognition, setUseParallelRecognition] = useState(true)
  const [recognitionInfo, setRecognitionInfo] = useState<any>(null)

  // 加载真实OCR记录数据
  const loadRecords = useCallback(async (page = 1) => {
    setRecordsLoading(true)
    try {
      const result = await ocrService.getHistory({
        page,
        limit: 20,
        ocrType: typeFilter === 'all' ? '' : typeFilter
      })

      if (result.success) {
        // 转换API记录格式为组件需要的格式
        const convertedRecords = result.data.map((record): OcrRecord => ({
          ...record,
          timestamp: record.createdAt,
          status: record.success ? 'success' : 'failed',
          data: {
            name: record.drugInfo?.name || record.text.substring(0, 20) || '未识别',
            id: record.id,
            ...record.drugInfo
          },
          confidence: record.confidence / 100, // 转换为0-1范围
          processedBy: record.userId
        }))
        
        setRecords(convertedRecords)
        setTotalPages(Math.ceil(result.pagination.total / result.pagination.limit))
      } else {
        toast.error(result.error || '加载记录失败')
        // 降级到模拟数据
        setRecords(generateMockOcrData())
      }
    } catch (error) {
      console.error('加载OCR记录失败:', error)
      toast.error('加载记录失败，使用演示数据')
      // 降级到模拟数据
      setRecords(generateMockOcrData())
    } finally {
      setRecordsLoading(false)
    }
  }, [typeFilter])

  // 删除记录
  const deleteRecord = useCallback(async (recordId: string) => {
    try {
      const result = await ocrService.deleteRecord(recordId)
      if (result.success) {
        toast.success('删除成功')
        setRecords(records.filter(record => record.id !== recordId))
      } else {
        toast.error(result.error || '删除失败')
      }
    } catch (error) {
      console.error('删除记录失败:', error)
      toast.error('删除失败')
    }
  }, [records])

  // 组件挂载时加载数据
  useEffect(() => {
    loadRecords(currentPage)
  }, [loadRecords, currentPage])

  // 类型过滤器变化时重新加载
  useEffect(() => {
    setCurrentPage(1)
    loadRecords(1)
  }, [typeFilter])

  // 过滤记录
  const filteredRecords = useMemo(() => {
    return records.filter(record => {
      const matchesSearch = searchTerm === '' || 
        record.data.name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
        record.data.id?.toLowerCase().includes(searchTerm.toLowerCase()) ||
        record.processedBy?.toLowerCase().includes(searchTerm.toLowerCase())
      
      const matchesType = typeFilter === 'all' || record.type === typeFilter
      const matchesStatus = statusFilter === 'all' || record.status === statusFilter
      
      return matchesSearch && matchesType && matchesStatus
    })
  }, [records, searchTerm, typeFilter, statusFilter])

  // 统计数据
  const stats = useMemo(() => {
    const total = records.length
    const successful = records.filter(r => r.status === 'success').length
    const failed = records.filter(r => r.status === 'failed').length
    const pending = records.filter(r => r.status === 'pending').length
    
    const drugCount = records.filter(r => r.type === 'drug').length
    const doctorCount = records.filter(r => r.type === 'doctor').length
    const patientCount = records.filter(r => r.type === 'patient').length
    
    const avgConfidence = records
      .filter(r => r.status === 'success')
      .reduce((sum, r) => sum + r.confidence, 0) / successful || 0
    
    return {
      total,
      successful,
      failed,
      pending,
      drugCount,
      doctorCount,
      patientCount,
      avgConfidence,
      successRate: total > 0 ? (successful / total * 100) : 0
    }
  }, [records])

  // 处理图片上传
  const handleImageUpload = useCallback(async (file: File, ocrType: 'drug' | 'doctor' | 'patient') => {
    if (!file) return

    if (!file.type.startsWith('image/')) {
      toast.error('请选择图片文件')
      return
    }

    if (file.size > 10 * 1024 * 1024) {
      toast.error('图片文件不能超过10MB')
      return
    }

    setSelectedImage(file)
    setImagePreview(URL.createObjectURL(file))
    setIsLoading(true)
    setUploadProgress(0)

    try {
      // 模拟上传进度
      const progressInterval = setInterval(() => {
        setUploadProgress(prev => {
          if (prev >= 90) {
            clearInterval(progressInterval)
            return prev
          }
          return prev + 10
        })
      }, 200)

      let result: any
      
      // 根据类型调用不同的OCR API
      switch (ocrType) {
        case 'drug':
          // 使用真实的OCR服务，会自动保存到数据库
          result = await ocrService.recognizeDrug(file, { parallel: useParallelRecognition })
          
          if (result.success) {
            setDrugInfo(result.data)
            setEditedDrugInfo(result.data)
            setRecognitionInfo(result.data)
            
            // 检查置信度并给出提示
            const confidence = result.data?.confidence || 0
            if (confidence < 60) {
              toast.warning(`识别完成，但置信度较低(${confidence}%)，请检查结果`)
            }
            
            // 如果使用了并行识别，显示额外信息
            if (result.data?.recognitionMode === 'parallel' && result.data?.serviceUsed) {
              toast.success(`${result.data?.recognitionMode === 'parallel' ? '并行' : '单一'}识别成功！使用${result.data?.serviceUsed}服务`)
            }
            
            // 识别成功后重新加载记录列表
            setTimeout(() => {
              loadRecords(currentPage)
            }, 1000)
          } else {
            throw new Error(result.error || '识别失败')
          }
          break
        case 'doctor':
          result = await recognizeDoctorId(file)
          setDoctorInfo(result)
          setEditedDoctorInfo(result)
          break
        case 'patient':
          result = await recognizePatientId(file)
          setPatientInfo(result)
          setEditedPatientInfo(result)
          break
      }
      
      clearInterval(progressInterval)
      setUploadProgress(100)
      
      // 根据置信度显示不同的成功消息
      const confidence = result.confidence || 0.85
      if (confidence >= 0.8) {
        toast.success(`识别成功！置信度: ${(confidence * 100).toFixed(1)}%`)
      } else if (confidence >= 0.6) {
        toast.success(`识别完成，置信度: ${(confidence * 100).toFixed(1)}%，请验证结果`)
      } else {
        toast.warning(`识别完成，置信度较低: ${(confidence * 100).toFixed(1)}%，建议重新拍摄`)
      }
    } catch (error) {
      console.error('OCR识别失败:', error)
      
      // 根据错误类型提供更友好的提示
      let errorMessage = '识别失败，使用模拟数据进行演示'
      if (error instanceof Error) {
        if (error.message.includes('404')) {
          errorMessage = 'OCR服务未启动，使用模拟数据进行演示'
        } else if (error.message.includes('Network Error')) {
          errorMessage = '网络连接失败，使用模拟数据进行演示'
        }
      }
      
      toast.error(errorMessage)
      
      // 使用模拟数据作为fallback
      let mockData: any
      switch (ocrType) {
        case 'drug':
          mockData = generateMockDrugInfo()
          setDrugInfo(mockData)
          setEditedDrugInfo(mockData)
          break
        case 'doctor':
          mockData = generateMockDoctorInfo()
          setDoctorInfo(mockData)
          setEditedDoctorInfo(mockData)
          break
        case 'patient':
          mockData = generateMockPatientInfo()
          setPatientInfo(mockData)
          setEditedPatientInfo(mockData)
          break
      }
      setUploadProgress(100)
    } finally {
      setIsLoading(false)
    }
  }, [])

  // 文件选择处理
  const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>, ocrType: 'drug' | 'doctor' | 'patient') => {
    const file = event.target.files?.[0]
    if (file) {
      handleImageUpload(file, ocrType)
    }
  }

  // 获取类型图标
  const getTypeIcon = (type: string) => {
    switch (type) {
      case 'drug':
      case 'drug_info': 
        return <IconPill className="h-4 w-4" />
      case 'doctor':
      case 'medical_id': 
        return <IconUserCheck className="h-4 w-4" />
      case 'patient': 
        return <IconUser className="h-4 w-4" />
      case 'document': 
        return <IconFileText className="h-4 w-4" />
      case 'general': 
        return <IconScan className="h-4 w-4" />
      default: 
        return <IconFileText className="h-4 w-4" />
    }
  }

  // 获取类型文本
  const getTypeText = (type: string) => {
    switch (type) {
      case 'drug':
      case 'drug_info': 
        return '药物识别'
      case 'doctor':
      case 'medical_id': 
        return '医生认证'
      case 'patient': 
        return '患者登记'
      case 'document': 
        return '文档识别'
      case 'general': 
        return '通用识别'
      default: 
        return '未知'
    }
  }

  // 获取状态颜色
  const getStatusColor = (status: string) => {
    switch (status) {
      case 'success': return 'bg-green-500'
      case 'failed': return 'bg-red-500'
      case 'pending': return 'bg-yellow-500'
      default: return 'bg-gray-500'
    }
  }

  // 获取状态文本
  const getStatusText = (status: string) => {
    switch (status) {
      case 'success': return '成功'
      case 'failed': return '失败'
      case 'pending': return '处理中'
      default: return '未知'
    }
  }

  return (
    <div className="h-full overflow-hidden bg-gradient-to-br from-blue-50 to-indigo-100">
      <div className="h-full flex flex-col p-6 space-y-6">
        {/* 头部标题 */}
        <div className="text-center space-y-2">
          <div className="flex items-center justify-center gap-3">
            <div className="p-3 bg-blue-600 rounded-lg">
              <IconScan className="h-6 w-6 text-white" />
            </div>
            <div>
              <h1 className="text-2xl font-bold text-gray-900">OCR识别中心</h1>
              <p className="text-gray-600">智能光学字符识别服务</p>
            </div>
          </div>
        </div>

        {/* 统计卡片 */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <Card>
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-gray-600">总识别次数</p>
                  <p className="text-xl font-bold text-gray-900">{stats.total}</p>
                </div>
                <IconFileText className="h-6 w-6 text-blue-600" />
              </div>
            </CardContent>
          </Card>
          
          <Card>
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-gray-600">成功率</p>
                  <p className="text-xl font-bold text-green-600">{stats.successRate.toFixed(1)}%</p>
                </div>
                <IconTrendingUp className="h-6 w-6 text-green-600" />
              </div>
            </CardContent>
          </Card>
          
          <Card>
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-gray-600">平均置信度</p>
                  <p className="text-xl font-bold text-purple-600">{(stats.avgConfidence * 100).toFixed(1)}%</p>
                </div>
                <IconEye className="h-6 w-6 text-purple-600" />
              </div>
            </CardContent>
          </Card>
          
          <Card>
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-gray-600">待处理</p>
                  <p className="text-xl font-bold text-orange-600">{stats.pending}</p>
                </div>
                <IconDatabase className="h-6 w-6 text-orange-600" />
              </div>
            </CardContent>
          </Card>
        </div>

        {/* 主要内容 */}
        <div className="flex-1 overflow-hidden">
          <Tabs value={activeOcrTab} onValueChange={setActiveOcrTab} className="h-full flex flex-col">
            <TabsList className="grid w-full grid-cols-4">
              <TabsTrigger value="overview">数据概览</TabsTrigger>
              <TabsTrigger value="drug">药物识别</TabsTrigger>
              <TabsTrigger value="doctor">医生认证</TabsTrigger>
              <TabsTrigger value="patient">患者登记</TabsTrigger>
            </TabsList>
            
            {/* 数据概览 */}
            <TabsContent value="overview" className="flex-1 overflow-auto space-y-4">
              {/* 搜索和过滤 */}
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <IconSearch className="h-5 w-5" />
                    数据查询
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
                    <div>
                      <Label htmlFor="search">搜索关键词</Label>
                      <Input
                        id="search"
                        placeholder="搜索姓名、ID..."
                        value={searchTerm}
                        onChange={(e) => setSearchTerm(e.target.value)}
                      />
                    </div>
                    
                    <div>
                      <Label htmlFor="typeFilter">识别类型</Label>
                      <Select value={typeFilter} onValueChange={setTypeFilter}>
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="all">全部类型</SelectItem>
                          <SelectItem value="drug_info">药物识别</SelectItem>
                          <SelectItem value="medical_id">医生认证</SelectItem>
                          <SelectItem value="document">文档识别</SelectItem>
                          <SelectItem value="general">通用识别</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                    
                    <div>
                      <Label htmlFor="statusFilter">处理状态</Label>
                      <Select value={statusFilter} onValueChange={setStatusFilter}>
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="all">全部状态</SelectItem>
                          <SelectItem value="success">成功</SelectItem>
                          <SelectItem value="failed">失败</SelectItem>
                          <SelectItem value="pending">处理中</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                    
                    <div className="flex items-end">
                      <Button 
                        variant="outline" 
                        onClick={() => {
                          setSearchTerm('')
                          setTypeFilter('all')
                          setStatusFilter('all')
                        }}
                        className="w-full"
                      >
                        <IconRefresh className="h-4 w-4 mr-2" />
                        重置
                      </Button>
                    </div>
                  </div>
                </CardContent>
              </Card>

              {/* 记录列表 */}
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center justify-between">
                    <span>识别记录</span>
                    <div className="flex items-center gap-2">
                      <Badge variant="secondary">{filteredRecords.length} 条记录</Badge>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => loadRecords(currentPage)}
                        disabled={recordsLoading}
                      >
                        <IconRefresh className={`h-4 w-4 mr-2 ${recordsLoading ? 'animate-spin' : ''}`} />
                        刷新
                      </Button>
                    </div>
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  {recordsLoading ? (
                    <div className="flex items-center justify-center py-8">
                      <IconRefresh className="h-6 w-6 animate-spin mr-2" />
                      <span>加载中...</span>
                    </div>
                  ) : (
                    <div className="space-y-3 max-h-96 overflow-y-auto">
                      {filteredRecords.length === 0 ? (
                        <div className="text-center py-8 text-gray-500">
                          <IconFileText className="h-12 w-12 mx-auto mb-2 text-gray-300" />
                          <p>暂无识别记录</p>
                        </div>
                      ) : (
                        filteredRecords.map((record) => (
                          <div key={record.id} className="border rounded-lg p-4 hover:bg-gray-50">
                            <div className="flex items-center justify-between mb-2">
                              <div className="flex items-center gap-2">
                                {getTypeIcon(record.type)}
                                <span className="font-medium">{getTypeText(record.type)}</span>
                                <Badge variant="outline">{record.data.name || record.data.id}</Badge>
                              </div>
                              <div className="flex items-center gap-2">
                                <div className={`w-2 h-2 rounded-full ${getStatusColor(record.status)}`}></div>
                                <Badge variant="outline">{getStatusText(record.status)}</Badge>
                                <span className="text-sm text-gray-500">
                                  {(record.confidence * 100).toFixed(1)}%
                                </span>
                                <Button
                                  variant="destructive"
                                  size="sm"
                                  onClick={(e) => {
                                    e.stopPropagation()
                                    deleteRecord(record.id)
                                  }}
                                >
                                  <IconTrash className="h-3 w-3" />
                                </Button>
                              </div>
                            </div>
                            
                            <div className="grid grid-cols-2 md:grid-cols-4 gap-2 text-sm text-gray-600">
                              <div>ID: {record.id}</div>
                              <div>时间: {new Date(record.timestamp).toLocaleString()}</div>
                              <div>处理人: {record.processedBy || '系统'}</div>
                              <div>状态: {getStatusText(record.status)}</div>
                            </div>
                            
                            {/* 显示药品信息 */}
                            {record.type === 'drug_info' && record.drugInfo && (
                              <div className="mt-2 pt-2 border-t">
                                <div className="text-xs text-gray-600 space-y-1">
                                  {record.drugInfo.name !== '未识别' && (
                                    <div><span className="font-medium">药品:</span> {record.drugInfo.name}</div>
                                  )}
                                  {record.drugInfo.specification !== '未识别' && (
                                    <div><span className="font-medium">规格:</span> {record.drugInfo.specification}</div>
                                  )}
                                  {record.drugInfo.manufacturer !== '未识别' && (
                                    <div><span className="font-medium">厂商:</span> {record.drugInfo.manufacturer}</div>
                                  )}
                                </div>
                              </div>
                            )}
                            
                            {/* 显示识别文本预览 */}
                            {record.text && (
                              <div className="mt-2 pt-2 border-t">
                                <div className="text-xs text-gray-600">
                                  <span className="font-medium">识别内容:</span> 
                                  {record.text.length > 100 ? `${record.text.substring(0, 100)}...` : record.text}
                                </div>
                              </div>
                            )}
                          </div>
                        ))
                      )}
                    </div>
                  )}
                  
                  {/* 分页 */}
                  {totalPages > 1 && (
                    <div className="flex items-center justify-center gap-2 mt-4">
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => setCurrentPage(Math.max(1, currentPage - 1))}
                        disabled={currentPage === 1 || recordsLoading}
                      >
                        上一页
                      </Button>
                      <span className="text-sm text-gray-500">
                        第 {currentPage} 页，共 {totalPages} 页
                      </span>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => setCurrentPage(Math.min(totalPages, currentPage + 1))}
                        disabled={currentPage === totalPages || recordsLoading}
                      >
                        下一页
                      </Button>
                    </div>
                  )}
                </CardContent>
              </Card>
            </TabsContent>

            {/* 药物识别 */}
            <TabsContent value="drug" className="flex-1 overflow-auto space-y-4">
              <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                {/* 图片上传区域 */}
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                      <IconPill className="h-5 w-5" />
                      药物标签识别
                    </CardTitle>
                    <CardDescription>
                      <div className="flex items-center gap-4 mt-2">
                        <label className="flex items-center gap-2 text-sm">
                          <input
                            type="checkbox"
                            checked={useParallelRecognition}
                            onChange={(e) => setUseParallelRecognition(e.target.checked)}
                            className="rounded"
                          />
                          并行识别模式（更高准确率）
                        </label>
                        {recognitionInfo && (
                          <div className="flex items-center gap-2">
                            <Badge variant="outline" className="text-xs">
                              {recognitionInfo.recognitionMode === 'parallel' ? '并行' : '单一'}识别
                              {recognitionInfo.confidence && ` | ${(recognitionInfo.confidence * 100).toFixed(1)}%`}
                            </Badge>
                            {recognitionInfo.fusedFrom && (
                              <Badge variant="secondary" className="text-xs">
                                融合: {recognitionInfo.fusedFrom.join(' + ')}
                              </Badge>
                            )}
                          </div>
                        )}
                      </div>
                    </CardDescription>
                  </CardHeader>
                  <CardContent>
                    <div
                      className="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center cursor-pointer hover:border-blue-500 transition-colors"
                      onClick={() => fileInputRef.current?.click()}
                    >
                      {imagePreview ? (
                        <div className="space-y-4">
                          <img
                            src={imagePreview}
                            alt="预览"
                            className="max-w-full max-h-32 mx-auto rounded-lg"
                          />
                          {isLoading && (
                            <div className="space-y-2">
                              <Progress value={uploadProgress} className="w-full" />
                              <p className="text-sm text-gray-500">识别中... {uploadProgress}%</p>
                            </div>
                          )}
                        </div>
                      ) : (
                        <div className="space-y-4">
                          <IconUpload className="h-8 w-8 text-gray-400 mx-auto" />
                          <div>
                            <p className="font-medium">上传药物标签</p>
                            <p className="text-sm text-gray-500">支持 JPG、PNG 格式</p>
                          </div>
                        </div>
                      )}
                    </div>
                    
                    <input
                      ref={fileInputRef}
                      type="file"
                      accept="image/*"
                      onChange={(e) => handleFileSelect(e, 'drug')}
                      className="hidden"
                    />
                  </CardContent>
                </Card>

                {/* 识别结果 */}
                {drugInfo && (
                  <Card>
                    <CardHeader>
                      <CardTitle className="flex items-center gap-2">
                        <IconCheck className="h-5 w-5 text-green-600" />
                        识别结果
                      </CardTitle>
                    </CardHeader>
                    <CardContent>
                      <div className="space-y-2 text-sm">
                        <div><strong>药品名称:</strong> {drugInfo.name || '未识别'}</div>
                        <div><strong>规格:</strong> {drugInfo.specification || '未识别'}</div>
                        <div><strong>生产企业:</strong> {drugInfo.manufacturer || '未识别'}</div>
                        <div><strong>批号:</strong> {drugInfo.batchNumber || '未识别'}</div>
                        <div><strong>有效期:</strong> {drugInfo.expiryDate || '未识别'}</div>
                        {drugInfo.approvalNumber && (
                          <div><strong>批准文号:</strong> {drugInfo.approvalNumber}</div>
                        )}
                        {drugInfo.indication && (
                          <div className="pt-2 border-t">
                            <strong>适应症:</strong> 
                            <div className="mt-1 text-gray-700 text-xs leading-relaxed">
                              {drugInfo.indication}
                            </div>
                          </div>
                        )}
                      </div>
                    </CardContent>
                  </Card>
                )}
              </div>
            </TabsContent>

            {/* 医生认证 */}
            <TabsContent value="doctor" className="flex-1 overflow-auto space-y-4">
              <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                      <IconUserCheck className="h-5 w-5" />
                      医生证件识别
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div
                      className="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center cursor-pointer hover:border-green-500 transition-colors"
                      onClick={() => fileInputRef.current?.click()}
                    >
                      <div className="space-y-4">
                        <IconId className="h-8 w-8 text-gray-400 mx-auto" />
                        <div>
                          <p className="font-medium">上传医生证件</p>
                          <p className="text-sm text-gray-500">执业证书或工作证</p>
                        </div>
                      </div>
                    </div>
                  </CardContent>
                </Card>

                {doctorInfo && (
                  <Card>
                    <CardHeader>
                      <CardTitle>医生信息</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <div className="space-y-2 text-sm">
                        <div><strong>姓名:</strong> {doctorInfo.name || '未识别'}</div>
                        <div><strong>证件号:</strong> {doctorInfo.id || '未识别'}</div>
                        <div><strong>科室:</strong> {doctorInfo.department || '未识别'}</div>
                        <div><strong>职位:</strong> {doctorInfo.position || '未识别'}</div>
                        <div><strong>执业证号:</strong> {doctorInfo.licenseNumber || '未识别'}</div>
                      </div>
                    </CardContent>
                  </Card>
                )}
              </div>
            </TabsContent>

            {/* 患者登记 */}
            <TabsContent value="patient" className="flex-1 overflow-auto space-y-4">
              <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                      <IconUser className="h-5 w-5" />
                      患者身份证识别
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div
                      className="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center cursor-pointer hover:border-purple-500 transition-colors"
                      onClick={() => fileInputRef.current?.click()}
                    >
                      <div className="space-y-4">
                        <IconIdBadge2 className="h-8 w-8 text-gray-400 mx-auto" />
                        <div>
                          <p className="font-medium">上传患者身份证</p>
                          <p className="text-sm text-gray-500">身份证正面</p>
                        </div>
                      </div>
                    </div>
                  </CardContent>
                </Card>

                {patientInfo && (
                  <Card>
                    <CardHeader>
                      <CardTitle>患者信息</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <div className="space-y-2 text-sm">
                        <div><strong>姓名:</strong> {patientInfo.name || '未识别'}</div>
                        <div><strong>身份证号:</strong> {patientInfo.id || '未识别'}</div>
                        <div><strong>联系电话:</strong> {patientInfo.phoneNumber || '未识别'}</div>
                        <div><strong>紧急联系人:</strong> {patientInfo.emergencyContact || '未识别'}</div>
                      </div>
                    </CardContent>
                  </Card>
                )}
              </div>
            </TabsContent>
          </Tabs>
        </div>
      </div>
    </div>
  )
}